<template>
  <div class="node_setting">
    <div class="setting-title">sql输入</div>
    <div class="setting_item">
      <el-form :model="form" label-width="110px">
        <el-form-item label="请输入SQL语句" required>
          <el-input
            v-model="form.sqlContent"
            style="min-width: 340px"
            :rows="8"
            type="textarea"
            @blur="validateNodeName"
          />
        </el-form-item>
      </el-form>
      <div v-if="tableNames.length" class="table_list">
        <span>提取的表名：{{ tableNames[0] }}</span>
        <!-- <span v-for="(name, index) in tableNames" :key="index" class="table-name">
          {{ name }}
        </span> -->
      </div>
      <!-- 重置按钮 -->
      <el-button class="mt-4" type="primary" @click="clearData">重置</el-button>
      <!-- 保存按钮 -->
      <el-button class="mt-4" type="primary" @click="saveData">保存</el-button>
      <!-- 保存按钮 -->
      <el-button class="mt-4" type="success" @click="formatSql">格式化SQL</el-button>
    </div>
  </div>
</template>
<script lang="ts">
export default { name: "SQLInputSetting" };
</script>
<script setup lang="ts">
import { format } from "sql-formatter";
import LogicFlow from "@logicflow/core";
import { MyLogicFlowPropertiesType } from "@/types/logic-flow";
import IndicatorManageAPI, {
  SQLParserRequestParameter,
  SQLParserResponse,
  TableListParameter,
  FieldColumnsConfig,
} from "@/api/strategy/strategy-index-database";
const props = defineProps<{
  lf?: LogicFlow;
  data: LogicFlow.NodeData | LogicFlow.EdgeData;
  parameter: TableListParameter;
}>();
const form = ref({
  sqlContent: "",
});
const isParser = ref(false);

const sqlParserRequestParameter = reactive<SQLParserRequestParameter>({});
const sqlParserResponse = ref<SQLParserResponse>();
const tableData = ref<FieldColumnsConfig[]>();
const tableName = ref<String>("");

const tableNames = ref<string[]>([]);

watch(
  () => props.data,
  (newVal) => {
    const { sqlContent } = newVal.properties as MyLogicFlowPropertiesType;
    form.value = {
      sqlContent: sqlContent || "",
    };
    props.lf?.setProperties(newVal.id, {
      ...form.value,
    });
  },
  {
    immediate: true,
  }
);

/**
 * * @description 验证表单
 */
const validateNodeName = (e: FocusEvent) => {
  const value = (e.target as HTMLInputElement).value;
  if (!value) {
    ElMessage.warning("SQL语句内容不可为空");
    form.value.sqlContent = props.data.text?.value || "";
  } else {
    props.lf?.updateText(props.data.id, value);
  }
};

//重置操作
const clearData = () => {
  form.value.sqlContent = "";
};
// 保存操作
const saveData = async () => {
  sqlParserRequestParameter.dataSourceId = props.parameter.id;
  sqlParserRequestParameter.sqlStr = form.value.sqlContent;
  await IndicatorManageAPI.SQLParser(sqlParserRequestParameter).then((data) => {
    sqlParserResponse.value = data;
    isParser.value = true;
  });
  tableName.value = sqlParserResponse.value?.tableNames[0]!;
  tableData.value = sqlParserResponse.value?.columnMetadataList.map((item) => {
    return {
      tableName: tableName.value,
      name: item.columnName,
      type: item.dataType,
      typeName: item.typeName,
      size: item.columnSize,
      digit: item.decimalDigits,
      comment: item.comment,
      nullable: item.nullable,
      pk: item.pk,
    };
  }) as unknown as FieldColumnsConfig[];
  if (props.lf) {
    props.lf?.setProperties(props.data.id, {
      sqlContent: form.value.sqlContent,
      tableName: tableName,
      tableData: tableData,
    });
  }
};

//格式化sql语句操作
const formatSql = async () => {
  // sqlParserRequestParameter.dataSourceId = props.parameter.id;
  // sqlParserRequestParameter.sqlStr = form.value.sqlContent;
  // await IndicatorManageAPI.SQLParser(sqlParserRequestParameter).then((data) => {
  //   sqlParserResponse.value = data;
  //   isParser.value = true;
  // });
  const formatted = format(form.value.sqlContent, {
    language: "mysql", // 强制指定格式化SQL语句
    tabWidth: 2,
    keywordCase: "upper",
    dataTypeCase: "upper",
    functionCase: "upper",
    identifierCase: "preserve",
    indentStyle: "standard",
    logicalOperatorNewline: "before",
    expressionWidth: 50,
    linesBetweenQueries: 1, // 每个查询之间保持1行空白
  });
  form.value.sqlContent = formatted;
};
onMounted(() => {
  // loadDataFromLocalStorage(); // 加载保存的数据
});
</script>
<style lang="scss" scoped>
.setting-title {
  padding: 10px 0;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  border-bottom: 1px solid #e9e9e9;
}

.setting-item {
  .setting-item-title {
    padding: 10px 0;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid #e9e9e9;
  }
}
</style>
